<template>
  <uni-popup ref="popup" type="bottom" background-color="#f7f7f7" :is-mask-click="false">
    <view class="close-container">
      <uni-icons type="closeempty" @tap="close" size="24"></uni-icons>
    </view>
    <scroll-view scroll-y class="sku-comtainer">
      <view v-for="(item, index) in list" :key="item.id_" class="sku-item">
        <image :src="item.img_" class="goods-img" mode="aspectFill" />
        <view class="sku-content">
          <view class="price">￥{{ item?.client_price_.toFixed(2) }}</view>
          <view class="format_"> 规格编号:<text>{{ item.code_ }}</text> 规格:<text>{{ item.format_ }}</text></view>
          <view class="stock_">库存:{{ item.stock_ }}</view>
          <view class="number-box">
            <uni-number-box :value="item.cart_number_" @change="e => change(e, index)" :min="0" :max="item.stock_" />
          </view>
        </view>
      </view>
    </scroll-view>
    <view class="footer">
      <view class="footer-header">
        数量<text class="number">{{ cartNum }}{{ unit_name_ }}</text>，
        金额<text class="total-price">￥{{ total?.toFixed(2) }}</text>
      </view>
      <button v-if="typeIdx_ == 1" class="btn-go-cart" @tap="goBuy">
        立即购买
      </button>
      <button v-else class="btn-go-pay" @tap="addCart">
        加入购物车
      </button>
    </view>
  </uni-popup>
</template>

<script setup lang="ts">
import { nextTick, ref, toRaw } from "vue"
import type { goodsSkuData, UpdateCartData, UpdateOrderData } from '@/types/goods';
import Apis from "@/services/modules/goods"
import { useOrderStore } from "@/stores/modules/order"

const { setOrder } = useOrderStore()

const props = withDefaults(defineProps<{
  isNowBuy: boolean
  isNoBar: boolean
}>(), {
  isNoBar: true
})

const popup = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()


const typeIdx_ = ref()
const unit_name_ = ref()
const list = ref<goodsSkuData[]>()
const getSkuGoodsDetailData = async (id: string, type_?: number) => {
  const { data } = await Apis.getSkuGoodsDetailApi(id)
  list.value = data.productList || []
  unit_name_.value = data.unit_name_
  getTotalCount()

  nextTick(() => {
    popup.value?.open('bottom')
    typeIdx_.value = type_
  })
}

defineExpose({
  refs: popup,
  getData: getSkuGoodsDetailData
})

const close = () => {
  popup.value?.close()
  uni.showTabBar()
}

const change = (e: number, index: number) => {
  list.value![index].cart_number_ = e
  getTotalCount()
}

const addCart = async () => {

  if (cartNum.value == 0) {
    return uni.showToast({
      title: '请先选择商品',
      icon: 'none',
      mask: true
    })
  }

  let arr: goodsSkuData[] = toRaw(list.value) || []
  let tempArr: UpdateCartData[] = []

  arr.map(item => {
    tempArr.push({
      product_id_: item.id_,
      goods_id_: item.goods_id_,
      number_: item.cart_number_,
      unit_id_: item.unit_id_
    })
  })

  if (tempArr.length === 0) {
    return uni.showToast({
      icon: "error"
    })
  }


  await Apis.updateCartApi(tempArr)
  popup.value?.close()
  props.isNoBar && uni.showTabBar()
  uni.showToast({
    icon: "success",
    title: "添加成功"
  })
}

const goBuy = async () => {
  let arr: goodsSkuData[] = toRaw(list.value) || []
  let tempArr: UpdateOrderData[] = []

  arr.map(item => {
    if (item.cart_number_) {
      tempArr.push({
        productId: item.id_,
        qty: item.cart_number_
      })
    }
  })

  if (tempArr.length === 0) {
    return uni.showToast({
      icon: "error"
    })
  }

  const { data } = await Apis.updateCartByProductListApi(tempArr)

  setOrder(data)
  popup.value?.close()
  uni.navigateTo({ url: '/pages/order/create-order' })
}

const cartNum = ref()
const total = ref()
const getTotalCount = () => {

  const pdList: goodsSkuData[] = list.value || []

  let cartNumer = 0;
  let totalAmout = 0;
  pdList.map(item => {
    let price_ = item.client_price_

    if (item.tieredPriceVos) {
      item.tieredPriceVos.map(it => {
        if (it.minQty <= item.cart_number_ && (item.cart_number_ <= it.maxQty || it.maxQty === null)) {
          price_ = it.price
        }
      })
    }

    cartNumer += item.cart_number_
    totalAmout += price_ * item.cart_number_
  })

  cartNum.value = cartNumer
  total.value = totalAmout

}

</script>

<style lang="scss">
page {
  z-index: 1;
}

.close-container {
  padding: 8px 12px;
  display: flex;
  justify-content: flex-end;
}

.sku-comtainer {
  padding: 0 6px;
  max-height: 60vh;

  .sku-item {
    display: flex;
    justify-content: flex-start;
    background: #fff;
    margin-bottom: 12px;
    padding: 6px;
    font-size: 14px;

    .goods-img {
      width: 60px;
      height: 60px;
    }

    .sku-content {
      margin-left: 12px;
      flex: 1;

      .price {
        color: red;
        font-size: 20px;
        font-weight: 600;
        padding-bottom: 6px;
      }

      .format_ {
        padding-bottom: 6px;
      }

      .stock_ {
        padding-bottom: 6px;
      }

      .number-box {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
}

.footer {
  background-color: #fff;

  .footer-header {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 8px 12px;
    font-size: 12px;

    .total-price {
      color: red;
      font-size: 18px;
      font-weight: 600;
    }
  }
}


:deep(.uni-popup) {
  z-index: 999 !important;
}

@mixin btnStyle($color ) {
  border-color: $color;
  background-color: $color;
  color: #fff;
  margin-left: 0;
  margin-right: 0;
}

.btn-go-cart {
  @include btnStyle($uni-color-error)
}

.btn-go-pay {
  @include btnStyle($uni-color-warning)
}
</style>

